package com.huawei.statistics.config;

import com.huawei.statistics.security.cache.ShiroCacheManager;
import com.huawei.statistics.security.credential.CustomCredentials;
import com.huawei.statistics.security.filter.PassThruFilter;
import com.huawei.statistics.security.quartz.QuartzSessionValidationScheduler2;
import com.huawei.statistics.security.realm.UserRealm;
import com.huawei.statistics.security.session.RedisSessionDao;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by op on 2017/11/3.
 */
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //拦截器.
        Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>();
        // 配置不会被拦截的链接 顺序判断
        filterChainDefinitionMap.put("/static/**", "anon");
        filterChainDefinitionMap.put("/anchor/changePwd", "anon");
        filterChainDefinitionMap.put("/anchor/aboutMf", "anon");
        filterChainDefinitionMap.put("/anchor/**", "authc");
        //filterChainDefinitionMap.put("/org/**", "authc");
        //filterChainDefinitionMap.put("/org/**", "roles[org_manager]");


        //配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
        //filterChainDefinitionMap.put("/logout", "logout");
        //<!-- 过滤链定义，从上向下顺序执行，一般将/**放在最为下边 -->:这是一个坑呢，一不小心代码就不好使了;
        //<!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
        //filterChainDefinitionMap.put("/**", "authc");
        // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
        shiroFilterFactoryBean.setLoginUrl("/sso/loginPage");
        // 登录成功后要跳转的链接
       // shiroFilterFactoryBean.setSuccessUrl("/index");


        //未授权界面;
        //shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        PassThruFilter passThruFilter=new PassThruFilter();
        Map<String,Filter> filterMap=new HashMap<>();
        filterMap.put("authc",passThruFilter);
        shiroFilterFactoryBean.setFilters(filterMap);
        return shiroFilterFactoryBean;
    }

    @Bean
    public UserRealm myShiroRealm(){
        UserRealm myShiroRealm = new UserRealm();
        myShiroRealm.setCachingEnabled(true);
        myShiroRealm.setCacheManager(getCacheManager());
        CustomCredentials customCredentials=new CustomCredentials();
        myShiroRealm.setCredentialsMatcher(customCredentials);
        return myShiroRealm;
    }


    @Bean
    public DefaultWebSecurityManager securityManager(){
        DefaultWebSecurityManager securityManager =  new DefaultWebSecurityManager();
        securityManager.setRealm(myShiroRealm());
        securityManager.setCacheManager(getCacheManager());
        securityManager.setRememberMeManager(getCookieRememberMeManager());
        securityManager.setSessionManager(getSessionManager());
        return securityManager;
    }

    @Bean
    public RedisSessionDao getSessionDao(){
        RedisSessionDao redisSessionDao=new RedisSessionDao();
        redisSessionDao.setActiveSessionsCacheName("shiro-activeSessionCache");
        JavaUuidSessionIdGenerator javaUuidSessionIdGenerator=new JavaUuidSessionIdGenerator();
        redisSessionDao.setSessionIdGenerator(javaUuidSessionIdGenerator);
        return redisSessionDao;
    }

    @Bean
    public DefaultWebSessionManager getSessionManager(){
        DefaultWebSessionManager sessionManager=new DefaultWebSessionManager();
        sessionManager.setSessionIdUrlRewritingEnabled(false);
        sessionManager.setGlobalSessionTimeout(1800000);// 1800000 ：30分钟 450000
        sessionManager.setDeleteInvalidSessions(true);
        SimpleCookie simpleCookie=new SimpleCookie("sid");
        simpleCookie.setHttpOnly(true);
        simpleCookie.setMaxAge(1800000);//30天
        sessionManager.setSessionIdCookieEnabled(true);
        sessionManager.setSessionValidationSchedulerEnabled(true);



        sessionManager.setSessionDAO(getSessionDao());

        QuartzSessionValidationScheduler2 validationScheduler2=new QuartzSessionValidationScheduler2();
        validationScheduler2.setSessionManager(sessionManager);
        validationScheduler2.setSessionValidationInterval(1800000);
        sessionManager.setSessionValidationScheduler(validationScheduler2);
        return sessionManager;
    }

    @Bean
    public CookieRememberMeManager getCookieRememberMeManager(){
        CookieRememberMeManager cookieRememberMeManager=new CookieRememberMeManager();
        SimpleCookie simpleCookie=new SimpleCookie("rememberMe");
        simpleCookie.setHttpOnly(true);
        simpleCookie.setMaxAge(2592000);//30天
        cookieRememberMeManager.setCookie(simpleCookie);
        cookieRememberMeManager.setCipherKey(Base64.decode("4AvVhmFLUs0KTA3Kprsdag=="));
        return cookieRememberMeManager;
    }

    @Bean
    public ShiroCacheManager getCacheManager(){
        return new ShiroCacheManager();
    }

    @Bean
    public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor(){
        return new LifecycleBeanPostProcessor();
    }

    /**
     * 注册DelegatingFilterProxy（Shiro）
     *
     * @return
     * @author SHANHY
     * @create  2016年1月13日
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
        filterRegistration.setFilter(new DelegatingFilterProxy("shiroFilter"));
        //  该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理
        filterRegistration.addInitParameter("targetFilterLifecycle", "true");
        filterRegistration.setEnabled(true);
        filterRegistration.addUrlPatterns("/*");
        return filterRegistration;
    }

}
